package cn.itcast.dewu.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static cn.itcast.dewu.utils.RedisConstants.CACHE_NULL_TTL;
import static cn.itcast.dewu.utils.RedisConstants.LOCK_GOODS_KEY;


@Slf4j
@Component
//封装Redis的工具类以方便后续使用
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //将任意地java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    //将任意的Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds//加秒
                (unit.toSeconds(time)));
    }



    //根据指定的key查询缓存,将反序列化为指定类型,用于缓存空值的方式解决缓存穿透问题
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type
            , Function<ID, R> dbFallback //函数式编程,用于写sql的
            , Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //从redis查询数据库缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //存在的直接返回
            return JSONUtil.toBean(json, type);
        }
        //不存在的根据id查询数据库
        R r = dbFallback.apply(id);
        //不存在返回错误
        if (r == null) {
            //将空值存入redis 并设置一定的过期时间
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //查询数据库存在  则写入redis
        this.set(key, r, time, unit); //调用方法写入redis

        return r;
    }


    /*加入线程池 10个线程
     * */
    private static final ExecutorService CACHE_REBULD_EXECUTOR = Executors.newFixedThreadPool(10);

    //根据指定的key查询缓存,并反序列化为指定类型,利用逻辑过期缓存解决缓存击穿问题
    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Object value, Class<R> type
            , Function<ID, R> dbFallback //函数式编程
            , Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //从redis查询商铺的缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (StrUtil.isBlank(json)) {
            return null;  //如果不存在直接返回空
        }
        //命中先把json序列化成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean(json, type);
        //做逻辑过期
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期
            return r;
        }
        //过期
        //获取互斥锁
        String lockKey = LOCK_GOODS_KEY  + id;
        boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if (isLock) {
            CACHE_REBULD_EXECUTOR.submit(() -> {

                try {
                    //成功则开启独立的线程,实现缓存重建
                    R r1 = dbFallback.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //一定要释放锁
                    unLock(lockKey);
                }
            });
        }

        return r;
    }

    //拿到锁
    private boolean tryLock(String key) {
        Boolean falg = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(falg);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
